package com.xyy.saas.payment.util.mq;

import com.xyy.saas.payment.common.RocketMqGroup;
import com.xyy.saas.payment.common.RocketMqTopic;
import com.xyy.saas.payment.payment.core.dto.RefundDto;
import com.xyy.saas.payment.payment.core.service.PaymentService;
import com.xyy.saas.payment.util.JSONUtils;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.common.UtilAll;
import org.apache.rocketmq.common.consumer.ConsumeFromWhere;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.ConsumeMode;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQPushConsumerLifecycleListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author wangtianqi
 * @date 2019/12/2 12:09
 */
@Service
@RocketMQMessageListener(topic = RocketMqTopic.TOPIC_RETRY_REFUND, consumerGroup = RocketMqGroup.GROUP_RETRY_REFUND, consumeMode = ConsumeMode.CONCURRENTLY)
public class RetryRefundConsumer implements RocketMQListener<MessageExt>, RocketMQPushConsumerLifecycleListener {

    private static final Logger LOGGER = LoggerFactory.getLogger(RetryRefundConsumer.class);

    @Autowired
    private PaymentService paymentService;

    @Override
    public void onMessage(MessageExt message) {
        String body = new String(message.getBody());
        try {
            LOGGER.info("RetryRefundConsumer#onMessage body:{}", body);
            RefundDto refundDto = JSONUtils.parse2Object(body, RefundDto.class);
            refundDto.setCount(refundDto.getCount() + 1);
            paymentService.refundAsync(refundDto);
        } catch (Exception e) {
            LOGGER.error("RetryRefundConsumer#onMessage consumer error body:{}", body, e);
        }
    }


    @Override
    public void prepareStart(DefaultMQPushConsumer consumer) {
        consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_FIRST_OFFSET);
        consumer.setConsumeTimestamp(UtilAll.timeMillisToHumanString3(System.currentTimeMillis()));
    }
}